package com.lcf.system.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.framework.exception.SysException;
import com.lcf.system.dao.SysUserDao;
import com.lcf.system.dto.user.LoginDTO;
import com.lcf.system.entity.SysUser;
import com.lcf.system.entity.UserScore;
import com.lcf.system.service.AuthService;
import jakarta.annotation.Resource;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * 用户表(User)表服务实现类
 *
 * @author lcf
 * @since 2025-02-19 13:27:56
 */
@Service("authService")
public class AuthServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements AuthService {
    @Resource
    private WxMaService wxMaService;

    /**
     * 小程序授权
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void miniAppLogin(String code) {
        try {
            String openId = wxMaService.getUserService().getSessionInfo(code).getOpenid();
            boolean exists = Db.lambdaQuery(SysUser.class).eq(SysUser::getOpenId, openId).exists();
            if (!exists) {
                new SysUser(openId, "编号" + RandomUtil.randomNumbers(6)).insert();
                new UserScore(openId).insert();
            }
            StpUtil.login(openId);
        } catch (WxErrorException e) {
            throw new SysException(e);
        }
    }

    @Override
    public void login(LoginDTO loginDTO) {
        SysUser one = Db.lambdaQuery(SysUser.class).eq(SysUser::getUsername, loginDTO.getUsername()).one();
        if (one == null || !Objects.equals(one.getPassword(), loginDTO.getPassword())) {
            throw new SysException("账号或密码错误");
        }

        StpUtil.login(one.getOpenId());
    }
}

